package com.atom.module.mvvm.base.view.fragment

import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.databinding.ViewDataBinding
import com.atom.module.mvvm.base.viewmodel.AbstractBaseViewModel

abstract class AbstractBaseMVVMFragment<V : ViewDataBinding, VM : AbstractBaseViewModel<*>> :
    AbstractMVVMFragment<V, VM>() {

    override fun initViewBinding(binding: V, viewModel: VM) {
        super.initViewBinding(binding, viewModel)
        viewModel.finishAction.observe(this) {
            requireActivity().finish()
        }

        viewModel.onBackPressedAction.observe(this) {
            requireActivity().onBackPressed()
        }

        viewModel.startActivityAction.observe(this) { pack ->
            val value = pack
            val clz = value[AbstractBaseViewModel.ParameterField.CLASS] as Class<*>
            val bundle = value[AbstractBaseViewModel.ParameterField.BUNDLE] as Bundle?
            startActivity(clz, bundle)
        }
        viewModel.startActivityForResultAction.observe(this) { pack ->
            val value = pack
            val clz = value[AbstractBaseViewModel.ParameterField.CLASS] as Class<*>
            val requestCode = value[AbstractBaseViewModel.ParameterField.REQUEST] as Int
            val bundle = value[AbstractBaseViewModel.ParameterField.BUNDLE] as Bundle?
            startActivityForResult(clz, requestCode, bundle)
        }

        viewModel.toastAction.observe(this) { pack ->
            toastShow(pack)
        }
    }

    fun startActivity(clz: Class<*>, bundle: Bundle? = null) {
        val intent = Intent(requireActivity(), clz)
        if (bundle != null) {
            intent.putExtras(bundle)
        }
        startActivity(intent)
    }

    fun startActivityForResult(clz: Class<*>, requestCode: Int, bundle: Bundle? = null) {
        val intent = Intent(requireActivity(), clz)
        if (bundle != null) {
            intent.putExtras(bundle)
        }
        startActivityForResult(intent, requestCode)
    }

    fun toastShow(value: String) {
        Toast.makeText(requireContext(), value, Toast.LENGTH_LONG).show()
    }

}
